import os
import subprocess

import loguru

from cmake import CmakeDepends
import re
from ruamel import yaml
import mantiDB
from ruamel.yaml import YAML
from yaml_tool import read_yaml_file
from yaml_tool import write_yaml_file
PRE_ANALYSE_MAP_PATH = 'pre_analyse_map.yaml'

# 返回 CmakeDepends



class PreAnalyseMapMaker:
    def __init__(self, cmake_dir, modules_dir, map_path):
        self.cmake_dir = cmake_dir
        self.modules_dir = modules_dir
        self.map_path = map_path

    def pre_analyse(self):
        # cmake dir
        for root, _, files in os.walk(self.cmake_dir):
            for file in files:
                basename, extension = os.path.splitext(file)
                file_path = os.path.join(root, file)
                if extension == '.cmake':
                    cmake = CmakeDepends()
                    cmake.parse(file_path)
                    VAR_MAP = {'QT_MAJOR_VERSION': ['5', '6']}
                    loguru.logger.info(f"Processing File {file_path} ......")
                    depends = cmake.save_only_depends(root, VAR_MAP, f"{file}-mid-depends.yaml")
                    find_order_set = set()
                    for condition, find_orders in depends.items():
                        find_order_set.update(find_orders)
                    yml = yaml.YAML()

                    # 写回合并后的内容
                    with open(self.map_path, 'a', encoding='utf-8') as pre_analyse_map:
                        yml.dump({file:list(find_order_set)}, pre_analyse_map)

        # module dir
        for root, _, files in os.walk(self.modules_dir):
            for file in files:
                basename, extension = os.path.splitext(file)
                file_path = os.path.join(root, file)
                if extension == '.cmake' and ('Find' in file or 'Config' in file):
                    cmake = CmakeDepends()
                    cmake.parse(file_path)
                    VAR_MAP = {'QT_MAJOR_VERSION': ['5', '6']}
                    loguru.logger.info(f"Processing File {file_path} ......")
                    depends = cmake.save_only_depends(root, VAR_MAP, f"{file}-mid-depends.yaml")
                    find_order_set = set()
                    for condition, find_orders in depends.items():
                        find_order_set.update(find_orders)
                    yml = yaml.YAML()

                    # 写回合并后的内容
                    with open(self.map_path, 'a', encoding='utf-8') as pre_analyse_map:
                        yml.dump({file:list(find_order_set)}, pre_analyse_map)


    def filter_map(self, output_path):
        map = read_yaml_file(self.map_path)

        for cmake_file, find_orders in map.items():
            need_to_remove = []
            for find_order in find_orders:
                if '$' in find_order:
                    find_orders.remove(find_order)
            # 移除非法find指令
            for i in need_to_remove:
                find_orders.remove(i)

        yml = yaml.YAML()
        # 写回合并后的内容
        with open(output_path, 'w', encoding='utf-8') as pre_analyse_map:
            yml.dump(map, pre_analyse_map)



if __name__ == '__main__':
    pre_analyse_make = PreAnalyseMapMaker("package-mapping-test\cmake","package-mapping-test\Modules", PRE_ANALYSE_MAP_PATH )
    pre_analyse_make.pre_analyse()
    pre_analyse_make.filter_map('filtered_map.yaml')